package com.lxl.priv.bak;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvException;
import org.apache.commons.lang3.ArrayUtils;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        String inputFile = "input.csv";
        String outputFile = "output.csv";
        String newColumnHeader = "New Column";
        String newColumnValue = "New Value";

        addColumnToCsv(inputFile, outputFile, newColumnHeader, newColumnValue);
    }

    public static void addColumnToCsv(String inputFile, String outputFile, String newColumnHeader, String newColumnValue) {
        try (CSVReader reader = new CSVReader(new FileReader(inputFile));
             CSVWriter writer = new CSVWriter(new FileWriter(outputFile))) {

            List<String[]> allRows = reader.readAll();
            List<String[]> modifiedRows = allRows.stream().map(row -> {
                String[] newRow = new String[row.length + 1];
                System.arraycopy(row, 0, newRow, 0, row.length);
                newRow[newRow.length - 1] = newColumnValue;
                return newRow;
            }).collect(Collectors.toList());

            writer.writeNext(ArrayUtils.add(allRows.get(0), newColumnHeader));
            for (String[] row : modifiedRows) {
                writer.writeNext(row);
            }
        } catch (IOException | CsvException e) {
            e.printStackTrace();
        }
    }
}
